<?php


namespace app\api\controller\User;


use app\api\controller\BaseController;
use app\api\model\User\UserFansModel;
use app\api\model\User\UserModel;
use app\api\model\User\UserVerifyCodeModel;
use app\api\model\User\UserWalletModel;
use app\api\validate\UserValidate;
use app\Utils\AliDaYuSMS;
use app\Utils\ImageUtil;
use app\Utils\Util;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class Login extends BaseController
{
    /**
     * @api {post} /register 用户注册
     * @apiGroup 用户
     * @apiParam {string} mobile 手机号
     * @apiParam {string} password 密码
     * @apiParam {string} invite_code 邀请码
     * @apiParam {string} code 验证码
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function registerUser(Request $request)
    {
        $param = $request->param();
        //验证数据
        try {
            validate(UserValidate::class)->scene('register')->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return Util::returnJson(self::CODE_ERROR, null, $e->getError());
        }

        $mobile = !empty($param['mobile']) ? $param['mobile'] : "";
        $password = !empty($param['password']) ? md5($param['password']) : "";
        //默认头像
        $head_img = ImageUtil::i()->replaceUrl(!empty($this->setting['default_head']) ? $this->setting['default_head'] : "");
        //邀请码
        $invite_code = !empty($param['invite_code']) ? $param['invite_code'] : "";
        if (!empty($invite_code)) {
            $agent_user = UserModel::getUserWhere([['invite_code', '=', $invite_code]]);
            if (!empty($agent_user['id'])) {
                //增加邀请人数
                UserWalletModel::referralsIn($agent_user['id']);
            }
        }

        //验证短信验证码
        $data = AliDaYuSMS::i()->verifyCode(1, $mobile, $param['code']);
        if ($data['code'] != 0) return Util::returnJson(self::CODE_ERROR, null, $data['msg']);
        Db::startTrans();
        try {
            //邀请码
            $invite_code = $this->getInviteCode();
            $sn = UserModel::generateUID();
            $data = [
                'account' => $mobile,
                'sn' => $sn,
                'mobile' => $mobile,
                'password' => $password,
                'level_id' => 0,
                'parent_uid' => !empty($agent_user) ? $agent_user['id'] : 0,
                'head_img' => $head_img,
                'nickname' => "mf_" . $mobile,
                'invite_code' => $invite_code,
                'up_time' => date("Y-m-d H:i:s", time()),
                'add_time' => date("Y-m-d H:i:s", time())
            ];
            $id = UserModel::addUser($data);
            if ($id) {
                $data_fans = [
                    'type' => 1,
                    'uid' => $id,
                    'head_img' => $head_img,
                    'nickname' => "mf_" . $mobile,
                    'mobile' => $mobile,
                    'up_time' => date("Y-m-d H:i:s", time()),
                    'add_time' => date("Y-m-d H:i:s", time())
                ];
                $fans_id = UserFansModel::addUserFans($data_fans);
                if ($fans_id) {
                    $data_wallet = [
                        'uid' => $id,
                        'add_time' => date("Y-m-d H:i:s", time()),
                    ];
                    UserWalletModel::addUserWallet($data_wallet);
                    Db::commit();
                    return Util::returnJson(self::CODE_SUCCESS, null, "注册成功");
                } else {
                    Db::rollBack();
                    return Util::returnJson(self::CODE_ERROR, null, "注册失败");
                }
            } else {
                Db::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "注册失败");
            }
        } catch (\Exception $e) {
            Db::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "注册失败");
        }
    }

    /**
     * @api {post} /app_login 登录
     * @apiGroup 用户
     * @apiParam {string} mobile 手机号
     * @apiParam {string} password 密码
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getAppLogin(Request $request)
    {
        $param = $request->param();
        $account = !empty($param['mobile']) ? $param['mobile'] : "";
        $password = !empty($param['password']) ? md5($param['password']) : "";

        $user = UserFansModel::getUserFansWhereJoin([['u.account', '=', $account]]);
        if (!empty($user)) {
            if ($user['password'] === $password) {
                $token = md5($user['account'] . time());
                $save = [
                    'token' => $token
                ];
                $flag = UserModel::updateUserWhere([['id', '=', $user['id']]], $save);
                if ($flag) {
                    $user['token'] = $token;
                    return Util::returnJson(self::CODE_SUCCESS, $user, "登录成功");
                } else {
                    return Util::returnJson(self::CODE_ERROR, null, "登录失败");
                }
            } else {
                return Util::returnJson(self::CODE_ERROR, null, "账号或密码错误2");
            }
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "账号或密码错误1");
        }

    }

    /**
     * 微信第三方授权登录
     * @param Request $request
     */
    public function getWxLogin(Request $request)
    {

    }

    /**
     * @api {post} /edit_user_password 忘记修改密码
     * @apiGroup 用户
     * @apiParam {string} mobile 手机号
     * @apiParam {string} code 验证码
     * @apiParam {string} password 密码
     * @apiParam {string} repassword 确认密码
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function editUserPassword(Request $request)
    {
        $param = $request->param();

        //验证数据
        try {
            validate(UserValidate::class)->scene('forget_password')->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return Util::returnJson(self::CODE_ERROR, null, $e->getError());
        }

        $mobile = !empty($param['mobile']) ? $param['mobile'] : "";
        $verify_code = !empty($param['code']) ? $param['code'] : "";
        $password = !empty($param['password']) ? $param['password'] : "";
        $repassword = !empty($param['repassword']) ? $param['repassword'] : "";
        if (md5($password) == md5($repassword)) {
            $data = AliDaYuSMS::i()->verifyCode(2, $mobile, $verify_code);
            if ($data['code'] == 0) {
                $save = [
                    'password' => md5($password),
                    'up_time' => date("Y-m-d H:i:s", time())
                ];
                $flag = UserModel::updateUserWhere([['mobile', '=', $mobile]], $save);
                if ($flag) {
                    return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
                } else {
                    return Util::returnJson(self::CODE_ERROR, null, "修改失败");
                }
            } else {
                return Util::returnJson(self::CODE_ERROR, null, $data['msg']);
            }
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "两次密码不一致");
        }
    }

}